/*
 *
 *      Copyright (c) 2018-2025, cloud All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: cloud
 *
 */

package com.fuyao.cloud.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyao.cloud.admin.api.entity.EgdOrgOuinfo;
import com.fuyao.cloud.admin.api.entity.SysDept;
import com.fuyao.cloud.admin.mapper.EgdOrgOuinfoMapper;
import com.fuyao.cloud.admin.service.EgdOuInfoService;
import com.fuyao.cloud.admin.service.SysDeptService;
import com.fuyao.cloud.common.data.resolver.ParamResolver;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author cloud
 * @since 2018-01-20
 */
@Service
@Slf4j
@AllArgsConstructor
public class EgdOuInfoServiceImpl extends ServiceImpl<EgdOrgOuinfoMapper, EgdOrgOuinfo> implements EgdOuInfoService {

    private final EgdOrgOuinfoMapper egdOrgOuinfoMapper;
    private final SysDeptService deptService;

    public boolean syncOaOuInfoToDept() {
        List<EgdOrgOuinfo> ouInfoList = egdOrgOuinfoMapper.selectOuInfoList();
        LambdaQueryWrapper<SysDept> eqFullCodeQuery = Wrappers.<SysDept>query().lambda().eq(SysDept::getFullCode, ParamResolver.getStr("DEFAULT_DEPT_FULLCODE", "GZHDJ"));
        SysDept parentDept = CollUtil.getFirst(deptService.list(eqFullCodeQuery));

        // 过滤祖级节点
        ouInfoList = ouInfoList.stream().filter(orgOuinfo -> (orgOuinfo.getParentId() != null && orgOuinfo.getParentId() > 0)).collect(Collectors.toList());

        ouInfoList.forEach(ouInfo -> {
            SysDept sysDept = deptService.getDeptByFullCode(ouInfo.getFullcode());
            if (ObjectUtil.isNotEmpty(sysDept)) {
                updateDept(ouInfo, sysDept, parentDept.getDeptId());
            } else {
                addDept(ouInfo, parentDept.getDeptId(), parentDept.getTenantId());
            }
        });
        log.info("同步单位信息成功：{}", LocalDateTime.now());
        return true;
    }

    /**
     * 添加部门信息
     *
     * @param ouInfo       oa单位信息
     * @param deptParentId 最大单位id
     * @param tenantId     租户id
     */
    private void addDept(EgdOrgOuinfo ouInfo, Long deptParentId, Long tenantId) {
        SysDept sysDept = new SysDept();
        sysDept.setName(ouInfo.getName());
        sysDept.setCode(ouInfo.getCode());
        sysDept.setFullCode(ouInfo.getFullcode());
        sysDept.setFullName(ouInfo.getFullname());
        sysDept.setDelFlag((ouInfo.getStatus().equals(0)? "0" : "1"));
        sysDept.setCreateTime(LocalDateTime.now());
        sysDept.setSortOrder(Integer.parseInt(ouInfo.getOrderNo()));
        sysDept.setPinyin(ouInfo.getPinyin());
        sysDept.setStatus(ouInfo.getStatus());
        sysDept.setType(ouInfo.getType());
        sysDept.setParentId(deptParentId);
        sysDept.setTenantId(tenantId);

        EgdOrgOuinfo parent = egdOrgOuinfoMapper.selectById(ouInfo.getParentId());
        SysDept parentDept = deptService.getDeptByFullCode(parent.getFullcode());
        if (ObjectUtil.isNotEmpty(parentDept)) {
            sysDept.setParentId(parentDept.getDeptId());
        }
        this.deptService.save(sysDept);
    }

    /**
     * 修改同步单位信息
     *
     * @param ouInfo       oa单位信息
     * @param sysDept      人事部门信息
     * @param deptParentId 最大单位id
     */
    private void updateDept(EgdOrgOuinfo ouInfo, SysDept sysDept, Long deptParentId) {
        sysDept.setName(ouInfo.getName());
        sysDept.setFullName(ouInfo.getFullname());
        sysDept.setDelFlag((ouInfo.getStatus().equals(0)? "0" : "1"));
        sysDept.setPinyin(ouInfo.getPinyin());
        sysDept.setType(ouInfo.getType());
        sysDept.setStatus(ouInfo.getStatus());
        sysDept.setSortOrder(Integer.parseInt(ouInfo.getOrderNo()));
        // 处理父级
        if (ouInfo.getParentId() != null && ouInfo.getParentId() > 0) {
            EgdOrgOuinfo parent = egdOrgOuinfoMapper.selectById(ouInfo.getParentId());
            SysDept parentDept = deptService.getDeptByFullCode(parent.getFullcode());
            if (ObjectUtil.isNotEmpty(parentDept)) {
                sysDept.setParentId(parentDept.getDeptId());
            }
        }
        sysDept.setUpdateTime(LocalDateTime.now());
        deptService.updateDept(sysDept);
    }
}
